//implementation of a correlation attack
//this version uses 32-bit shift register 
//each object has an lfsr
//before the attack the lfsr must be initiated 
//thus the length and the feedback polynomial must be set
//in the attack all initial states of the lfsr are tested
//for each state an lfsr output of the same length 
//as the keystream are generated
//the state that gives the output with the smallest distance 
//to the keystream are returned
#include "corrAttack.h"

//attack, return the initial state that generates the sequence
//with the smallest distance to the keystream
//initPoly and correct length must be set before calling attack
unsigned long CorrAttack::attack(BitVector32 keystream){
  unsigned long minState=0;
  unsigned long length=keystream.length();
  unsigned long minweight=keystream.weight();
  unsigned long maxKey=(1uL<<lfsr.getLength())-1;
  unsigned long nbr32word=length>>5;
  unsigned long nbrBits=length&0x1f;
  //run through all keys
  for(unsigned long key=1;key<=maxKey;key++){
    lfsr.initState(key);
    BitVector32 lfsrSeq;
    //generate lfsr sequence from key
    for(unsigned long i=0;i<nbr32word;i++)
      lfsrSeq.appendWord32(lfsr.clock32());
    for(unsigned long i=0;i<nbrBits;i++)
      lfsrSeq.appendBit(lfsr.clock());
    //compare with keystream
    lfsrSeq.xorOp(keystream);
    unsigned long w=lfsrSeq.weight();
    if(w<minweight){
      minweight=w;
      minState=key;
    }
  }

  return minState;

}
